﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using thousandclear.Data;
using thousandClear.Areas.Admin.Models;
using thousandClear.Util.Setting;

namespace thousandClear.Areas.Admin.Controllers
{
    public class ShopOrderListController : Controller
    {
        // GET: Admin/Order?page={page}&count={count}
        public ActionResult Index(int? page, int? count, int? status, string sn, string mobile)
        {
            page = page ?? 1;
            count = count ?? 10;

            int totalCount = 0;
            int totalPage = 1;
            int currentPage = page.Value;
            int pageCount = count.Value;

            List<OrderViewModel> list = new List<OrderViewModel>();

            ViewBag.Status = status?.ToString() ?? string.Empty;
            ViewBag.SN = sn;
            ViewBag.Mobile = mobile;

            using (var db = new qianjingEntities())
            {
                var query = db.O_Order_Info.AsQueryable();

                if (status != null)
                {
                    query = query.Where(a => a.Status == status);
                }

                if (!string.IsNullOrEmpty(sn))
                {
                    query = query.Where(a => a.SerialNo == sn);
                }

                if (!string.IsNullOrEmpty(mobile))
                {
                    var tt = db.O_Address.FirstOrDefault(p => p.osaPhone.Trim() == mobile.Trim());

                    var csm1 = db.O_Customer.FirstOrDefault(a => a.OCID == tt.oasOCID);

                    if (csm1 != null)
                    {
                        query = query.Where(a => a.OpenId == csm1.ocOpenid);
                    }
                    else
                    {
                        query = query.Where(a => a.OpenId == "abc123");
                    }
                }

                totalCount = query.Count();

                var records = query.OrderByDescending(a => a.Id).Skip((page.Value - 1) * count.Value).Take(count.Value).ToList();

                foreach (var item in records)
                {
                    O_Customer csm = null;

                    if (!string.IsNullOrEmpty(item.OpenId))
                    {
                        csm = db.O_Customer.FirstOrDefault(a => a.ocOpenid == item.OpenId);
                    }

                    var ty = db.O_Address.FirstOrDefault(p => p.oasOCID == csm.OCID);

                    list.Add(new OrderViewModel
                    {
                        Id = item.Id,
                        SerialNo = item.SerialNo,
                        ConsumerName = csm == null ? "N/A" : ty.oasName,
                        ConsumerMobile = csm == null ? "N/A" : ty.osaPhone,
                        OrderTime = item.OrderTime?.ToString("yyyy-MM-dd HH:mm") ?? "N/A",
                        Amount = item.Amount.Value.ToString("#0.00"),
                        //PostFee = ((item.PostFee ?? 0) / 100).ToString("#0.00"),
                        //Weight = ((item.Weight ?? 0) / 1000).ToString("#0.000"),
                        Status = item.Status ?? 0,
                    });
                }
            }

            ViewBag.Orders = JsonConvert.SerializeObject(list);

            ViewBag.TotalCount = totalCount;
            totalPage = int.Parse((totalCount / count).ToString()) + (totalCount % count == 0 ? 0 : 1);
            ViewBag.TotalPage = totalPage;
            ViewBag.CurrentPage = currentPage;
            ViewBag.PageCount = pageCount;

            return View();
        }

        // GET: Admin/Order/Detail/{id}
        public ActionResult Detail(long? id, bool? success, string errmsg)
        {
            ViewBag.Success = success ?? true;
            ViewBag.ErrMsg = errmsg;

            AppSetting setting = new AppSetting();
            OrderDetailModel model = new OrderDetailModel();

            using (qianjingEntities db = new qianjingEntities())
            {
                var record = db.O_Order_Info.FirstOrDefault(a => a.Id == id);

                var consfo = db.O_Customer.FirstOrDefault(p => p.ocOpenid == record.OpenId);
                var consumer_info = db.O_Address.FirstOrDefault(p => p.oasOCID == consfo.OCID);

                if (record != null)
                {
                    model.Id = record.Id;
                    model.SerialNo = record.SerialNo;
                    model.Amount = record.Amount.Value.ToString("#0.00");
                    //model.PostFee = (record.PostFee.Value / 100.00).ToString("#0.00");
                    model.PostBillNo = record.PostBillNo;
                    //model.Weight = (record.Weight.Value / 1000.00).ToString("#0.000");
                    model.Status = record.Status ?? 0;
                    model.Remark = string.IsNullOrEmpty(record.Remark) ? "N/A" : record.Remark;

                    model.OrderPerson = consumer_info.oasName;
                    model.OrderMobile = consumer_info.osaPhone;
                    model.OrderTime = record.OrderTime.Value.ToString("yyyy-MM-dd HH:mm:ss");

                    model.ReceivePerson = record.ReceiveMan;
                    model.ReceiveZipCode = record.ReceiveZip;
                    model.ReceiveMobile = record.ReceiveMobile;

                    //var region = db.v_region_info.FirstOrDefault(a => a.Id == record.ReceiveRegion);

                    //if (region != null)
                    //{
                    //    model.ReceiveAddress = string.Format("{0} {1}", region.FullName, record.ReceiveAddress);
                    //}
                    //else
                    //{
                    //    model.ReceiveAddress = record.ReceiveAddress;
                    //}

                    model.ReceiveAddress = record.ReceiveAddress;



                    model.PayTradeNo = record.SerialNo;
                    model.PayState = record.PayState ?? 0;
                    model.PayTranId = string.IsNullOrEmpty(record.PayTranId) ? "N/A" : record.PayTranId;
                    model.PayMode = record.PayMode ?? 0;
                    model.PayTime = record.PayTime == null ? "N/A" : record.PayTime.Value.ToString("yyyy-MM-dd HH:mm:ss");

                    //model.RefundTradeNo = record.RefundNo;
                    //model.RefundTranId = string.IsNullOrEmpty(record.RefundTranId) ? "N/A" : record.RefundTranId;
                    //model.RefundState = record.RefundState ?? 0;
                    //model.RefundMode = record.RefundMode ?? 0;
                    //model.RefundTime = record.RefundTime == null ? "N/A" : record.RefundTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                    //model.RefundFee = ((record.RefundFee ?? 0) / 100.00).ToString("#0.00");

                    var detailInfo = db.D_Order_list_info.OrderByDescending(a => a.CreatedTime).Where(pp => pp.Id == record.Id);

                    foreach (var item in detailInfo)
                    {
                        var good_info = db.D_ShopGood.FirstOrDefault(oo => oo.DSGID == item.GoodId);
                        model.Goods.Add(new OrderGoodModel
                        {
                            Name = item.GoodName,
                            no = good_info.squm == null ? 0 : good_info.squm.Value,
                            Amount = (item.Amount.Value).ToString("#0.00"),
                            Quantity = item.Quantity.Value,
                            //Weight = (item.good_info.Weight.Value / 1000.00).ToString("#0.000"),
                            ImgUrl = string.Format("{0}/{1}/{2}", setting.AppDomainName, "/statics/upload/good/image", good_info.ThumbUrl),
                        });
                    }
                }
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult Deliver(long orderId, string postBillNo)
        {
            using (qianjingEntities db = new qianjingEntities())
            {
                var record = db.O_Order_Info.FirstOrDefault(a => a.Id == orderId);

                if (record != null)
                {
                    record.PostBillNo = postBillNo;
                    record.Status = 2;
                }

                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

    }
}